﻿using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Xml;
//using StockMonitor.Helper;

//using StockMonitor.Configuration;
using System.Threading;
using Tigera.T_Definition;
using Tigera.LibCodeUtils;
using System.IO;
using Tigera.Framework.Windows.Forms;
using Tigera.LibCommon;


namespace StockMonitor.UserControls
{



    public partial class UCBusinessQuery : UserControl
    {
        #region Ctor.

        public UCBusinessQuery()
            : base()
        {
            FormLogin.Login();
            InitializeComponent();
            this.DataBindings.Add("Enabled", AuthUserService.Instance, "Logined", false, DataSourceUpdateMode.OnPropertyChanged);
        }


        public string Title
        {
            get
            {
                return "交易查询";
            }

        }


        #endregion

        #region MidUserControl Members

        public void Onload()
        {
            this.dgvBusinessQ.AutoGenerateColumns = false;
            this.dgvBusinessHistory.AutoGenerateColumns = false;
            ThreadPool.QueueUserWorkItem(o =>
            {
                RefreshTodayBusiness();
            });
        }



        #endregion

        #region Event Handlers

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            RefreshTodayBusiness();
        }

        private void btnBusinessQ_Click(object sender, EventArgs e)
        {
            QueryHistoryBusiness(this.dtpBeginDate.Value, this.dtpEndDate.Value);
        }

        private void cbAutoRefresh_CheckedChanged(object sender, EventArgs e)
        {
            if (cbAutoRefresh.Checked)
            {
                if (String.IsNullOrEmpty(this.textBoxTimer.Text))
                {
                    return;
                }
                timeAutoBQ.Enabled = true;

                timeAutoBQ.Interval = int.Parse(this.textBoxTimer.Text) * 1000;
            }
            else
                timeAutoBQ.Enabled = false;
        }

        private void timeAutoBQ_Tick(object sender, EventArgs e)
        {
            RefreshTodayBusiness();
        }

        #endregion

        #region Methods

        /// <summary>
        /// 刷新今日成交记录.
        /// </summary>
        /// <remarks>
        /// 代码编写：<author>LANCEZHANG-PC\zhangxl</author><br/>
        /// 编写时间：<datetime>2012-10-16 5:47 PM</datetime>
        /// </remarks>
        private void RefreshTodayBusiness()
        {
            try
            {
                //if (AppMgr.MQMode)
                //{
                TradeCMD cmd = new TradeCMD();
                cmd.Ope = TradeRiskOpe.TodayBusinessRecordQuery;

                AppMgr.Instance.Mqclient.OnList_ResultF402 -= TradeContext.Instance.hS_OnList_ResultF402;
                AppMgr.Instance.Mqclient.OnList_ResultF402 += TradeContext.Instance.hS_OnList_ResultF402;
                TradeContext.Instance.OnTodayDataRecieved -= Instance_OnTodayDataRecieved;
                TradeContext.Instance.OnTodayDataRecieved += new EventHandler(Instance_OnTodayDataRecieved);

                AppMgr.Instance.Mqclient.SendDataTo(AppMgr.TradeRiskExName, ESHelper.Pack(ref cmd));



            }
            catch (Exception ex)
            {
                //Log.Exception("系统错误", ex);
            }


        }

        void Instance_OnTodayDataRecieved(object sender, EventArgs e)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(() => UpdateTodayBusinessUI()));
            }
            else
            {
                UpdateTodayBusinessUI();
            }

        }

        private void UpdateTodayBusinessUI()
        {
            this.lbLastUpdatedTimeBQ.Text = DateTime.Now.ToString("hh:mm:ss");
            TradeContext.Instance.TodayBusiness.Sort((a, b) => (a.SerialNo - b.SerialNo));


            List<BusinessRecord> tmp = new List<BusinessRecord>();

            int dealedorderid = -1;

            foreach (var item in TradeContext.Instance.TodayBusiness)
            {
                if (item.SerialNo != dealedorderid)
                {
                    tmp.Add(item);
                }
                dealedorderid = item.SerialNo;
            }
            TradeContext.Instance.TodayBusiness = tmp;

            TradeContext.Instance.TodayBusiness.Sort((a, b) => (b.SerialNo - a.SerialNo));
            this.dgvBusinessQ.DataSource = new SortableBindingList<BusinessRecord>(TradeContext.Instance.TodayBusiness);
            this.dgvBusinessQ.Update();
            this.dgvBusinessQ.Refresh();


            var total = GetDealSummurys(TradeContext.Instance.TodayBusiness);
            this.dataGridViewTotal.DataSource = new SortableBindingList<DealedSummury>(total);
            this.dataGridViewTotal.Update();
            this.dataGridViewTotal.Refresh();
        }


        private List<DealedSummury> GetDealSummurys(List<BusinessRecord> input)
        {
            List<DealedSummury> ret = new List<DealedSummury>();
            var groups = from item in input group item by item.StockCode into codegroup orderby codegroup.Key select codegroup;
            foreach (var cdgup in groups)
            {
                DealedSummury sum = new DealedSummury();
                var bsgroups = from item in cdgup group item by item.Entrustbs into minigroup orderby minigroup.Key select minigroup;

                foreach (var minigp in bsgroups)
                {

                    if (minigp.Count() > 0 && minigp.First().Entrustbs == EntrustBs.买入)
                    {
                        sum.Code = minigp.First().StockCode;
                        sum.Name = minigp.First().StockName;

                        foreach (var item in minigp)
                        {
                            sum.BuyDealedNum += (int)item.BusinessAmount;
                            sum.BuyDealMoney += item.BusinessBalance;
                        }
                        sum.BuyAvaMoney = sum.BuyDealMoney / sum.BuyDealedNum;
                    }
                    if (minigp.Count() > 0 && minigp.First().Entrustbs == EntrustBs.卖出)
                    {
                        sum.Code = minigp.First().StockCode;
                        sum.Name = minigp.First().StockName;
                        foreach (var item in minigp)
                        {
                            sum.SellDealedNum += (int)item.BusinessAmount;
                            sum.SellDealMoney += item.BusinessBalance;
                        }
                        sum.SellAvaMoney = sum.SellDealMoney / sum.SellDealedNum;
                    }

                }

                ret.Add(sum);

            }

            return ret;



            //input.GroupBy(item =>)
        }

        private void QueryHistoryBusiness(DateTime dtStart, DateTime dtEnd)
        {
            //try
            //{
            //if (AppMgr.MQMode)
            //{
            //  MessageBox.Show("此功能尚未实现");
            return;

            TradeCMD cmd = new TradeCMD();
            cmd.Ope = TradeRiskOpe.HistoryBusinessRecordQuery;
            cmd.HisbusinessQueryStart = Convert.ToInt32(dtStart.ToString("yyyyMMdd"));
            cmd.HisbusinessQueryEnd = Convert.ToInt32(dtEnd.ToString("yyyyMMdd"));


            AppMgr.Instance.Mqclient.SendDataTo(AppMgr.TradeRiskExName, ESHelper.Pack(ref cmd));
            //}
            //else
            //{
            //this.dgvBusinessHistory.DataSource = new SortableBindingList<BusinessRecord>(TradeContext.Instance.UpdateHistoryBusiness(dtStart, dtEnd));
            //this.dgvBusinessHistory.Update();
            //this.dgvBusinessHistory.Refresh();
            //}

            //}
            //catch (Exception ex)
            //{
            //    //Log.Exception("系统错误", ex);
            //}
        }

        #endregion

        private void btn_Export_Click(object sender, EventArgs e)
        {
            if (this.dgvBusinessQ.RowCount > 0)
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
                saveFileDialog.FilterIndex = 0;
                saveFileDialog.RestoreDirectory = true;
                saveFileDialog.CreatePrompt = true;
                saveFileDialog.Title = "Export Excel File To";
                saveFileDialog.FileName = DateTime.Now.Date.ToString("yyyyMMdd");
                if (saveFileDialog.ShowDialog(this) != DialogResult.OK)
                {
                    return;
                }

                Stream myStream = saveFileDialog.OpenFile();
                //StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
                StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));

               
                try
                {
                    DumpTradeDetail(sw, dgvBusinessQ);
                    sw.WriteLine("");
                    sw.WriteLine("");
                    DumpTradeDetail(sw, dataGridViewTotal);
                    


                    
                    sw.Close();
                    myStream.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                finally
                {
                    sw.Close();
                    myStream.Close();
                }
            }
        }

        private void DumpTradeDetail(StreamWriter sw,System.Windows.Forms.DataGridView grid)
        {
            string str = "";
            //写标题
            for (int i = 0; i < grid.ColumnCount; i++)
            {
                if (i > 0)
                {
                    str += "\t";
                }
                str += grid.Columns[i].HeaderText;
            }
            sw.WriteLine(str);

            //写内容
            for (int j = 0; j < grid.Rows.Count; j++)
            {
                string tempStr = "";
                for (int k = 0; k < grid.Columns.Count; k++)
                {

                    if (k > 0)
                    {
                        tempStr += "\t";
                    }
                    grid.Rows[j].Cells[k].ValueType = typeof(string);
                    try
                    {
                        tempStr += grid.Rows[j].Cells[k].Value.ToString();
                    }
                    catch (Exception)
                    {
                        break;
                    }
                    
                }
                sw.WriteLine(tempStr);
            }
        }
    }

    public class DealedSummury
    {
        [DisplayNameAttribute("证券代码")]
        public string Code
        {
            get;
            set;
        }

        [DisplayNameAttribute("证券名称")]
        public string Name
        {
            get;
            set;
        }
        [DisplayNameAttribute("买入总量")]
        public int BuyDealedNum
        {
            get;
            set;
        }
        [DisplayNameAttribute("买入总费用")]
        public double BuyDealMoney
        {
            get;
            set;
        }
        [DisplayNameAttribute("买入均价")]
        public double BuyAvaMoney
        {
            get;
            set;
        }

        [DisplayNameAttribute("卖出总量")]
        public int SellDealedNum
        {
            get;
            set;
        }
        [DisplayNameAttribute("卖出总费用")]
        public double SellDealMoney
        {
            get;
            set;
        }
        [DisplayNameAttribute("卖出均价")]
        public double SellAvaMoney
        {
            get;
            set;
        }
    }

}
